<template>
  <div id="container" style="width: 100%; height: 100%;"></div>
</template>

<script>
import * as echarts from 'echarts';
// 导入本地数据
import graphData from '@/assets/es-miserables.json';

export default {
  name: 'EChartsGraph',
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    initChart() {
      const chartDom = document.getElementById('container');
      const myChart = echarts.init(chartDom, null, {
        renderer: 'canvas',
        useDirtyRect: false
      });
      let option;

      myChart.showLoading();
      // 直接使用本地导入的数据
      const graph = graphData
      myChart.hideLoading();
      graph.nodes.forEach(node => {
        node.label = {
          show: node.symbolSize > 30
        };
      });
      option = {
        title: {
          text: '产业链展示',
          subtext: 'Circular layout',
          top: 'bottom',
          left: 'right'
        },
        tooltip: {
          trigger: 'item',
          triggerOn: 'mousemove',
          formatter: function (params) {
            if (params.dataType === 'edge') {
              // 获取连线的源节点和目标节点名称
              const sourceNode = graph.nodes.find(node => node.id === params.data.source);
              const targetNode = graph.nodes.find(node => node.id === params.data.target);
              return `${sourceNode.name} -> ${targetNode.name} `;
            }
            return params.name;
          }
        },
        legend: [
          {
            data: graph.categories.map(a => a.name)
          }
        ],
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [
          {
            name: '链路传导',
            type: 'graph',
            layout: 'circular',
            circular: {
              rotateLabel: true
            },
            data: graph.nodes,
            links: graph.links,
            categories: graph.categories,
            roam: true,
            label: {
              position: 'right',
              formatter: '{b}'
            },
            lineStyle: {
              color: 'source',
              curveness: 0.3,
            },
            emphasis: {
              lineStyle: {
                width: 2
              }
            },
            edgeSymbol: ['circle', 'arrow'], // 定义连线的起点和终点符号
            edgeSymbolSize: [4, 6], // 定义连线的起点和终点符号大小
          }
        ]
      };
      myChart.setOption(option);
    },
    handleResize() {
      const chartDom = document.getElementById('container');
      const myChart = echarts.getInstanceByDom(chartDom);
      if (myChart) {
        myChart.resize();
      }
    }
  }
};
</script>

<style scoped>
/* 可以在这里添加额外的样式 */
</style>
